package com.atguigu.springcloud.controller;


import com.atguigu.springcloud.entity.CommonResult;
import com.atguigu.springcloud.entity.Payment;

import com.atguigu.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.annotation.Resources;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
public class PaymentController {

    @Resource
    private PaymentService service;

    @Value("${server.port}")
    private String port;

    @Resource
    private DiscoveryClient discoveryClient;

    @PostMapping("/payment/create")
    public CommonResult<Payment> insert(@RequestBody Payment payment){
        int result = service.create(payment);
        log.info("插入结果："+result);
        if (result>0){
            return new CommonResult(200,"插入成功,服务："+port,result);
        }else{
            return new CommonResult(500,"插入失败,服务："+port,result);
        }
    }

    @GetMapping("/payment/get/{id}")
    public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id){
        Payment result = service.getPaymentById(id);
        log.info("查询结果："+result);
        if (null != result){
            return new CommonResult(200,"获取成功,服务："+port,result);
        }else{
            return new CommonResult(500,"获取失败,服务："+port);
        }
    }

    @GetMapping("/payment/lb")
    public String lb(){
        return port;
    }


    /**
     * 服务发现列表
     * @return
     */
    @GetMapping("/payment/discovery")
    public Object getDiscovery(){
        List<String> services = discoveryClient.getServices();
        services.stream().forEach(System.out::println);

        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        instances.stream().forEach(System.out::println);
        return this.discoveryClient;
    }



    @GetMapping(value = "/feign/timeout")
    public String paymentFeignTimeout() {
      try {
        // 暂停3秒钟 模拟超时任务
        TimeUnit.SECONDS.sleep(3);
       } catch (InterruptedException e) {
        e.printStackTrace();
       }
      return port;
    }


    @GetMapping("/payment/zipkin")
    public String paymentZipkin(){
       return "hi ,i'am paymentzipkin server fall back，welcome to atguigu，O(∩_∩)O哈哈~";
    }


}
